<?php
require 'TVB/pms/pdes/common/util/UpdateMeta.class.php';
require_once 'TVB/VideoInfrastructure/Client/requires.php';
require 'TVB/VideoInfrastructure/Client/requires.php';
require_once('TVB/pms/pdes/action/VideoGetAction.class.php');

class VideoUpdateAction extends BaseAction 
{
    public $id;
    public $title;
	/**
	 * @filter datetime
	 * @label First On Air Date Time
	 */
    public $first_time_onair;
	/**
	 * @filter datetime
	 * @label Online Date Time
	 */
    public $online_date_time;
	/**
	 * @filter datetime
	 * @label Offline Date Time
	 */
    public $offline_date_time;
    public $country_allow_deny;
    public $country;
	public $ut;
	public $reset;
	public $from;
    public $edit_eps;
	/**
	 * @filter positive_number
	 * @maxLength 9
	 * @label On Air Episode No.
	 */
	public $onair_episode_no;
	public $old_onair_episode_no;
	public $programme_id;
    public $copyright_owner;
    public $copyright;
    public $mdes_status;
	public $act;
    public $modified_at;
    public $modified_by;

    public $chapter_id;
    public $highlighted_cast_roles;
    public $cast_dict_id;
    public $available_tag_types;
    public $tag;
	public $tags;
	#public $new_tag;
    public $infos;
    public $tvbcom_cat_id;
    public $language_id;
    /**
     * @maxLength 255
     * @label Chapter Title(chinese)
     */
    public $chapter_title_cn;
    /**
     * @maxLength 255
     * @label Chapter Title(english)
     */
    public $chapter_title_en;
    public $chapter_description_cn;
    public $chapter_description_en;

    public $deleted_chapters;
    public $attached_info;
  
	public $new_video_id;
    public $chapter_in_time_hour;
    public $chapter_in_time_minute;
    public $chapter_in_time_second;
    public $chapter_out_time_hour;
    public $chapter_out_time_minute;
    public $chapter_out_time_second;
    public $duration;
    public $exist_thumbnail_image;

    public $premium_flag;
    public $video_type;

    #for table video_subscription
    public $subscription_country_allow_deny;
    public $subscription_country;
    /**
     * @filter datetime
     * @label Online Date Time 
     */
    public $subscription_publish_datetime;
    /**
     * @filter datetime
     * @label Offline Date Time
     */
    public $subscription_expire_datetime;
    public $subscription_free;

    // for table video_premium
    public $premium_items;
    
    //for table video_ppv
    public $ppv_country;
    public $ppv_country_allow_deny;

    /**
     * @filter datetime
     * @label Online Date Time 
     */
    public $ppv_publish_datetime;
    
    /**
     * @filter datetime
     * @label Offline Date Time 
     */
    public $ppv_expire_datetime;

    public $subtitle_cn;
    public $subtitle_en;

	public function execute()
    {
        if (!is_null($this->reset))
		{
			$this->setData('id', $this->id);
			$this->setData('type', 'video');
			$this->setData('act', 'edit');
			$this->setData('from', $this->from);
			return 'reset';
		}

		Model::$dbo['w']->beginTransaction();
		$thumbnail_is_uploaded = false;
		try{
            $this->premium_flag = is_null( $this->premium_flag) ? 0 :  $this->premium_flag ;
			if ($this->ut!=TRUE && $this->act!='add' && $this->check_concurrent())
			{
				$this->init_page_data();
				$this->addError('concurrent', array('0105', 'Concurrent update found!'));
				return 'logic-error';
			}

			if (count($this->_errors) > 0)
			{
				$this->init_page_data();
				return "filter-error";
            }


            if(empty($this->first_time_onair)){
                $this->first_time_onair = '';
            }

            if(empty($this->programme_id)){
                $this->init_page_data();
                $this->addError('The Programme is not exist', array('0101', 'The Programme is not exist!'));
                return 'filter-error';
            }

            if(empty($this->online_date_time) || empty($this->offline_date_time)){
                $this->init_page_data();
                $this->addError('Publish Date/Time && Expire Date/Time', array('0033', 'Publish Date/Time && Expire Date/Time'));
                return 'filter-error';
            }

            if (!empty($this->online_date_time) && !empty($this->offline_date_time))
            {
                if ($this->online_date_time > $this->offline_date_time)
                {
                    $this->init_page_data();
                    $this->addError('Publish Date/Time && Expire Date/Time', array('0033', 'Publish Date/Time && Expire Date/Time'));
                    return 'filter-error';
                }
            }

           
            if(!empty($this->premium_items) && in_array('subscription',$this->premium_items))
            {
                if ($this->__check_subscription_datetime() == FALSE) {
                    $this->addError('Online Date Time / Offline Date Time', array('0205', 'Online Date Time / Offline Date Time'));
                    $this->init_page_data();
                    return 'filter-error';
                }
            }

			$programme = new programme;
			$programme_detail = $programme->get($this->programme_id);
			$folder_ids = $programme_detail->folders;
			
			$this->proof_programme_id = 0;
			if (!empty($folder_ids)) {
				$video_ids = folder::getItemByFolder($folder_ids, 'video');
				if (in_array($this->id, $video_ids)) {
					$this->proof_programme_id = $this->programme_id;
				}
			}

            $this->__update_video_subscription();
            
            if(!empty($this->premium_items) && in_array('ppv',$this->premium_items))
            {
                if ($this->__check_ppv_datetime() == FALSE) {
                    $this->addError('Online Date Time / Offline Date Time', array('0205', 'Online Date Time / Offline Date Time'));
                    $this->init_page_data();
                    return 'filter-error';
                }
            }
            $this->__update_video_ppv();


            if(strlen($this->premium_flag) > 0 )
            {
                $this->__update_video_premium();
            }
            else
            {
                $this->addError('Premium Items', array('0400', 'Use for premium'));
                $this->init_page_data();
                return 'filter-error';
            }

          
            if($this->onair_episode_no){
                $eid = episode::getEpisodeID($this->programme_id,$this->onair_episode_no);
                if(!$eid)
                {
                    $this->init_page_data();
                    $this->addError('Programme or Episode', array('0103', 'Programme or Episode'));
                    return 'logic-error';
                }
            }

            # replace thumbnail image
            if(!empty($_FILES))
            {
                if(UPLOAD_ERR_NO_FILE != $_FILES['thumbnail']['error']){
                    if(UPLOAD_ERR_OK == $_FILES['thumbnail']['error']){
                        $upload_status = CommonUtils::upload_image_to_ii($_FILES['thumbnail']['tmp_name']);
                        $thumbnail_is_uploaded = ( array_sum($upload_status['status']) == count($upload_status['status']) );
                        if($thumbnail_is_uploaded){
                            $this->ii_id = $upload_status['source_id'];
                            $this->thumbnail_url = $upload_status['thumbnail_url'];
                            $this->image_source_url = $upload_status['source_url'];
                        }
                    }

                    if(!$thumbnail_is_uploaded){
                        $this->init_page_data();
                        $this->addError('Thumbnail Image', array('0055', 'Replace Thumbnail Image'));
                        return 'logic-error';
                    }
                }
            }
            //check in/out time
            if ($this->check_chapter())
            {
                $this->init_page_data();
                return 'filter-error';
            }

            //check upload image
            $upload = $this->check_upload_image();

            //output upload error
            
            if(count($this->_errors) > 0){
                $this->init_page_data();
                return 'filter-error';
            }

            $this->setData("type", "video");

            if($this->act=='add'){
                $video_id = $this->update_video('create');
                $this->id = $video_id;
                $this->update_video_language();
            }else{
                $this->update_video_language();
                $this->update_video();
            }

			//for bug:7529    #modified by Albie Lu on 2011-10-26
			//$this->del_chapter();
			$this->del_chapter_physical();

            $this->add_chapter($upload);
            if (!is_null($this->new_video_id)) $this->move_chapter($this->id, $this->new_video_id);

            $meta_obj   =   new UpdateMeta('Video', $this->id);
            $meta_obj->UpdateAcl();
            $meta_obj->UpdateMeta('Programme');

            Model::$dbo['w']->commit();

            if ($this->edit_eps=='1' && $this->onair_episode_no) {
                $episode_id = episode::getEpisodeID($this->programme_id,$this->onair_episode_no);
                if (empty($episode_id)) {
                    $this->init_page_data();
                    $this->addError('On Air Episode Number Error', array('0057', 'On Air Episode Number Error'));
                    return 'logic-error';
                }

                $this->setData('act', 'edit');
                $this->setData('step', 2);
                $this->setData('id', $episode_id);
                return 'episode_edit';
            } 
            
            switch ($this->from) {
            case 'task':
                return 'task';
                break;
            case 'programme':
                $this->setData('type', 'programme');
                $this->setData('id', $this->programme_id);
                $this->setData('step', 2);
                $this->setData('act', 'edit#anchor-video');
                return 'programme_edit';
                break;
            default:
                return 'succ';
                break;
            }
        }
		catch(Exception $e)
		{
			if($thumbnail_is_uploaded && isset($this->ii_id)){ // remove thumbnail file
				$ii = new ImageInfrastructureClient();
				$ii->DeleteSource($this->ii_id);
			}

			error_log("Update Video Fails: {$this->id}" . var_export($e,1));
			error_log("Request: " . var_export($this, 1));

			Model::$dbo['w']->rollBack();

			return 'system-error';
		}
    }

    private function update_video($action='update')/*{{{*/
    {
		$now_time = date('c');
		$uploader = CommonUtils::get_user();
        $video    =   new video();

		if($action=='update'){
			$video  =   $video->get($this->id);
			Model::diff($video, $this);
		}else{
			$video->ii_id               = '';
			$video->ii_status           = AC::IMAGE_STATUS_WAITING;
			$video->thumbnail_url       = '';
			$video->image_source_url    = '';
			$video->vi_id               = '';
			$video->vi_status           = AC::VIDEO_STATUS_QUEUE;
			$video->video_params        = '';
			$video->source_url          = '';
			$video->status              = AC::STATUS_NEW;
			$video->created_at          = $now_time;
			$video->created_by          = $uploader;
			$video->premium_flag        = 0;
			$video->video_type          = 'O';
		}
        //$video->casts               =   $this->add_cast_field(null,$this->cast_dict_id);
        $video->casts               =   '';
       	$video->tags                =   $this->get_tags();
		$video->available_tag_types =   CommonUtils::get_allow_tags('video');
        $video->programme_id        =   $this->programme_id;
        $video->first_time_onair    =   $this->first_time_onair;
        $video->publish_datetime    =   $this->online_date_time;
        $video->expire_datetime     =   $this->offline_date_time;
        $video->modified_at         =   $now_time;
        $video->modified_by         =   $uploader;

        $video->copyright  = empty($this->copyright_owner) ? 'TVB' : trim($this->copyright_owner);
        $video->mdes_status = $this->mdes_status;
        $video->premium_flag = $this->premium_flag;
        $video->video_type = $this->video_type;

        if ('allow' ==  $this->country_allow_deny)
        {
            $video->country_allow_list  =   is_null($this->country) ? '' : ParseCountryCode::json2country($this->country); 
            $video->country_deny_list   =   'ALL';
        }
        else
        {
            $video->country_allow_list  =   'ALL';
            $video->country_deny_list  =   is_null($this->country) ? '' : ParseCountryCode::json2country($this->country); 
        }

		$update_id  =   Model::$dbo['w']->save($video);
		if($this->act != 'add'){
			$update_id = $this->id;
        }

		$video->add_change_log($this->proof_programme_id);
		folder_item::addFolderItemChangeLog('video', $update_id, $this->proof_programme_id);

        if($this->old_onair_episode_no != $this->onair_episode_no)
        {
            if($this->old_onair_episode_no)
            {
                $eid_old = episode::getEpisodeID($video->programme_id,$this->old_onair_episode_no);
                if(!empty($eid_old))
                {
                    Model::updateBySql('delete from `episode-video` where episode_id=:eid and video_id=:vid',array(':eid'=>$eid_old,':vid'=>$update_id));

					$episode_video = new episode_video;
					$episode_video->episode_id = $eid_old;
					$episode_video->video_id = $update_id;
			   		$episode_video->add_change_log($this->proof_programme_id, 0);
                }
            }

        }

		if ($this->onair_episode_no) {
			$episode_id = $eid = episode::getEpisodeID($video->programme_id,$this->onair_episode_no);
			Model::updateBySql('replace into `episode-video`(episode_id,video_id)values(:eid,:vid)',array(':eid'=>$eid,':vid'=>$update_id));

		   	$episode_video = new episode_video;
		   	$episode_video->episode_id = $episode_id;
		   	$episode_video->video_id = $update_id;
		   	$episode_video->add_change_log($this->proof_programme_id);
		}

		if ($update_id > 0)
		{
			if($this->act == 'add') {
				$this->addInfo("video:".AC::LOG_OP_CREATE.":".$update_id, "$action video success", json_encode($video));
			}else{
				$this->addInfo("video:".AC::LOG_OP_UPDATE.":".$update_id, "$action video success", json_encode($video));
			}
			return $update_id;
		}
		else
		{
			$this->addError("video:".AC::LOG_OP_UPDATE.":".$update_id, "$action video failed", json_encode($video));
			return false;
		}
    }/*}}}*/

    private function update_video_language()/*{{{*/
    {
		$en_langid = language::getLanguageID(AC::LANGUAGE_EN);
		$zh_langid = language::getLanguageID(AC::LANGUAGE_ZH);
		if($this->act == 'add'){
			$video_language = new video_language();
			$video_language->video_id    = $this->id;

			$video_language->language_id = $en_langid;
			$video_language->subtitle       = trim($this->subtitle_en);
			//$video_language->title       = trim($this->en_title);
			//$video_language->description = isset($this->en_description) ?  $this->en_description : '';
			Model::$dbo['w']->save_by_fields($video_language, array('video_id', 'language_id'));

			$video_language->language_id = $zh_langid;
			$video_language->title       = trim($this->title);
			$video_language->subtitle       = trim($this->subtitle_cn);
			//$video_language->description = isset($this->description) ? $this->description : '';
			Model::$dbo['w']->save_by_fields($video_language, array('video_id', 'language_id'));
		}else{
            $sql = "REPLACE INTO `video-language`(`video_id`, `language_id`, `title`, `description`,`subtitle`) VALUES(:video_id, :language_id, :title, :description, :subtitle)";
            $this->title = isset($this->title) ? trim($this->title) : '';
            $this->description = isset($this->description) ? $this->description : '';
            $this->subtitle_cn = isset($this->subtitle_cn) ? $this->subtitle_cn : '';
			Model::updateBySql($sql, array(
				':video_id' => $this->id, 
				':language_id' => $zh_langid, 
				':title' => $this->title, 
				':description' => $this->description, 
				':subtitle'=>$this->subtitle_cn)
			);
			Model::updateBySql($sql, array(
				':video_id' => $this->id, 
				':language_id' => $en_langid, 
				':title' => '', 
				':description' =>'', 
				':subtitle'=>$this->subtitle_en)
			);

			$video_language = new video_language;
			$video_language->video_id = $this->id;
			$video_language->language_id = $zh_langid;
			$video_language->title = $this->title; 
			$video_language->description = $this->description;
			$video_language->subtitle = $this->subtitle_cn;
			$video_language->add_change_log($this->proof_programme_id);

			$video_language->video_id = $this->id;
			$video_language->language_id = $en_langid;
			$video_language->title = ''; 
			$video_language->description = ''; 
			$video_language->subtitle = $this->subtitle_en;
			$video_language->add_change_log($this->proof_programme_id);
        }
        
        $primary_key = array(
            'video_id' => $this->id
        );
        $fields = array(
            'title', 
            'description'
        );
        CommonUtils::filterC2A0('video-language', $primary_key, $fields);

        return true;
    }/*}}}*/

	private function get_tags(){/*{{{*/
		$all_tags = array();
		if(isset($this->tag[13])){
			$sql = 'SELECT id  FROM tag t where system_label = :label and tag_type_id =13';
			foreach($this->tag[13] as $max => $tag){

				if( ($max) >= AC::SEO_MAX_TAG ) break;

				if(is_array($tag)){
					$t_id = Model::selectBySql($sql,array(':label'=>urldecode(trim($tag['new']))));
					if(empty($t_id))
					{
						$tag_obj = new tag();
						$tag_obj->parent_id = 0;
						$tag_obj->tag_type_id = 13;
						$tag_obj->system_label = urldecode(trim($tag['new']));
						$tag_obj->id = $tag_id = Model::$dbo['w']->save($tag_obj);
						$all_tags[] = $tag_id;

						$tag_obj->add_change_log();
					}
					else
					{
						$tid = $t_id[0]['id'];
						$all_tags[] = tag::IsParent($tid);
					}
				}
				else
				{
					$all_tags[] = $tag;
				}
			}
			$all_tags = array_slice(array_unique($all_tags), 0, AC::SEO_MAX_TAG);
		}
        return empty($all_tags) ? '' : implode(',',$all_tags);
	}/*}}}*/

	private function add_tag($chapter_id)/*{{{*/
	{
		$tag_arr = array();
		$tag_id  = explode(',',CommonUtils::get_allow_tags('chapter'));

		foreach ($tag_id as $id)
		{
			$sql_by_name = 'SELECT id  FROM tag t where system_label = :label and tag_type_id = :type';
			$sql_by_id   = 'SELECT system_label FROM tag t where id = :tid';
			if (isset($this->tag[$id][$chapter_id]))
			{
				foreach ($this->tag[$id][$chapter_id] as $value)
				{
					if (tag::isRestricted($id))
					{
						$tag_arr[] = $value;
					}
					else
                    {
                        if ( is_array($value) )
                        {
                            $t_id = Model::selectBySql($sql_by_name,array(':label'=>urldecode(trim($value['new'])),':type'=>$id));

                            if(empty($t_id))
                            {
                                $tag = new tag();
								$tag->parent_id = 0;
								$tag->tag_type_id = $id;
								$tag->system_label = urldecode(trim($value['new']));
								$tag->id = $ret = Model::$dbo["w"]->save($tag);
							    $tag_arr[] = $ret;

								$tag->add_change_log();
                            }
                            else
                            {
                                $_id = $t_id[0]['id'];
                                if('4' === $id)
                                {
                                    $ret = tag::getLibTag($_id);
                                    $ret = explode(',',$ret);
							        $tag_arr[] = $ret[0];
							        $tag_arr[] = isset($ret[1]) ? $ret[1] : '';
                                }
                                else
                                {
							        $ret = tag::IsParent($_id);
							        $tag_arr[] = $ret;
                                }
                            }
                        }
                        else
                        {
                            $data = Model::selectBySql($sql_by_id,array(':tid'=>trim($value)));

                            if(empty($data))
                            {
							    $tag_arr[] = $value;
                            }
                            else
                            {
                                if('4' === $id)
                                {
                                    $ret = tag::getLibTag($value);
                                    $ret = explode(',',$ret);
                                    $tag_arr[] = $ret[0];
							        $tag_arr[] = isset($ret[1]) ? $ret[1] : '';
                                }
                                else
                                {
                                    $ret = tag::IsParent($value);
							        $tag_arr[] = $ret;
                                }
                            }
                            
                        }
					}
				}
				$tag_arr = array_unique($tag_arr);
			}
		}
        $tag_arr = array_filter($tag_arr);
        return empty($tag_arr) ? '' : implode(",", $tag_arr);
	}/*}}}*/

	private function init_tag($chapter_id, $i)/*{{{*/
	{
		$tag_arr = array();
		$tag_id  = explode(',',CommonUtils::get_allow_tags('chapter'));

		foreach ($tag_id as $id)
		{
			if (isset($this->tag[$id][$chapter_id]))
			{
				foreach ($this->tag[$id][$chapter_id] as $value)
				{
					if(is_array($value)) 
					{
						$value = $value['new'];
						$tag_arr[$id][] = array('is_new'=>1,'system_label'=>urldecode(trim($value)), 'id'=>$value);
					}
					else
					{
						$tag = new tag();
						$tag_detail = $tag->get($value);
						$tag_arr[$id][] = array(
							'system_label'	=> urldecode($tag_detail->system_label), 
							'id'			=> $value
						);
					}
				}
			}
		}
       	return $tag_arr;
	}/*}}}*/
	
	private function num_to_sec($time_type, $i)/*{{{*/
	{
		if (!empty($time_type)) {
			return $time_type[0][$i]*3600 + $time_type[1][$i]*60 + $time_type[2][$i];
		} else {
            return '';
        }
	}/*}}}*/

	private function add_cast_field($chapter_id=null,$cast_dict_id)/*{{{*/
    {
        $cast_id_string = '';
        if(!empty($cast_dict_id))
        {
            $cast_id_array = array();
            foreach($cast_dict_id as $key => $cast_id)
            {
                if(is_array($cast_id) && $key == $chapter_id)
                {
                    foreach($cast_id as $chapter_cast_id)
                    {
                        $cast_id_array[] = $chapter_cast_id;
                       
                    }
                }
                //for video cast
                else if(!is_array($cast_id) && $chapter_id == null)
                {
                    $cast_id_array[] = $cast_id;
                }
            }
            $cast_id_string = implode(',',$cast_id_array);
        }
        return $cast_id_string;

	}/*}}}*/
	
	/**
	 * upload image and get image info
	 */
	private function upload_image($tmp_path)
	{
		$result   = CommonUtils::upload_image_to_ii($tmp_path);
		$uploaded = ( array_sum($result['status']) == count($result['status']) );
		if(!$uploaded) return 'upload';
		else return $result;
	}
	
	/**
	 * check upload image if valid
	 */
	private function check_upload_image()/*{{{*/
	{
		$upload_detail = array();
        $empty_image = false;
        $chapter_no = array();
           
		$len = count($this->chapter_id);
		for($i=0; $i<$len; $i++)
		{
            $tmp_name = $_FILES['screen_capture']['tmp_name'][$i];
			if ( empty($tmp_name) && empty($this->exist_thumbnail_image[$i]) )
			{
				$upload_detail[$i]['flag'] = false;
				$upload_detail[$i]['result'] = "upload error";
                $empty_image = true;
                $chapter_no[] = $i+1;
                continue;
            }
            if(!empty($tmp_name))
            {
                $upload = $this->upload_image($_FILES['screen_capture']['tmp_name'][$i]);
                if (!is_array($upload))
                {
                    $upload_detail[$i]['flag'] = false;
                    $upload_detail[$i]['result'] = "upload error";
                    $empty_image = true;
                    $chapter_no[] = $i+1;

                    //	$this->addError('Video chapter'.($i+1).'.Screen Capture', array('0055',  'Chapter '.($i+1).':Screen Capture'));
                }
                else
                {
                    $upload_detail[$i]['flag'] = true;
                    $upload_detail[$i]['result'] = $upload;
                }
            }
        }


        if( $empty_image  && $len >0 )
        {
            $this->init_page_data();
            $chap_no = implode(', ',$chapter_no);
            $this->addError('Chapter '.$chap_no.' Thumbnail Image', array('0055', 'Chapter '.$chap_no.' Thumbnail Image'));
            return 'logic-error';
        }

        return $upload_detail;
	}/*}}}*/


	/**
	 * check in_time and out_tim
	 */
	private function check_chapter()/*{{{*/
	{
		$len = count($this->chapter_id);
		$in_flag  = false;
		$out_flag = false;
		$in_null_flag  = false;
		$out_null_flag = false;
		$title_flag  = false;
		$tag_flag    = false;
        $video_duration = 0;
        $video_duration_real = substr($this->duration, 0, 2)*60*60 + substr($this->duration, 3, 2)*60 + substr($this->duration, 6); 

		for($i=0; $i<$len; $i++)
		{
			if ($this->chapter_title_cn[$i]=='' && $this->chapter_title_en[$i]== '')
			{
				$title_flag = true;
				break;
			}
			if ($this->chapter_in_time_hour[$i] == '' && $this->chapter_in_time_minute[$i] == '' && $this->chapter_in_time_second[$i] == '')
			{
				$in_null_flag = true;
				break;
			}
			if ($this->chapter_out_time_hour[$i] == '' && $this->chapter_out_time_minute[$i] == '' && $this->chapter_out_time_second[$i] == '')
			{
				$out_null_flag = true;
				break;
			}

			//length check
			$in_str1 = strlen($this->chapter_in_time_hour[$i]);
			$in_str2 = strlen($this->chapter_in_time_hour[$i]);
			$in_str3 = strlen($this->chapter_in_time_hour[$i]);
			$out_str1 = strlen($this->chapter_out_time_hour[$i]);
			$out_str2 = strlen($this->chapter_out_time_hour[$i]);
			$out_str3 = strlen($this->chapter_out_time_hour[$i]);
			if ($in_str1>8 || $in_str2>4 || $in_str3>4)
			{
				$in_flag = true;
				break;
			}
			if ($out_str1>9 || $out_str2>5 || $out_str3>5)
			{
				$out_flag = true;
				break;
			}

            $in_time = array(
                array($i => $this->chapter_in_time_hour[$i]),
                array($i => $this->chapter_in_time_minute[$i]),
                array($i => $this->chapter_in_time_second[$i])
            );
            $out_time = array(
                array($i => $this->chapter_out_time_hour[$i]),
                array($i => $this->chapter_out_time_minute[$i]),
                array($i => $this->chapter_out_time_second[$i])
            );

			$start_time =  $this->num_to_sec($in_time, $i);
			$end_time   =  $this->num_to_sec($out_time, $i);

            #Out time should larger than In time
			if (intval($start_time) >= intval($end_time)) {
			    $this->addError('cmp_time', array('0045', 'Chapter '.($i+1)));
                return TRUE;
            }

            #check video's duration  
            $video_duration += $end_time - $start_time;
            if (($video_duration > $video_duration_real) || ($end_time > $video_duration_real)) {
                $this->addError("Chapter's total duration is error", array('0058', "Chapter's total duration is error"));
                return TRUE;
            }
		}
		if ($in_flag)
		{
			$this->addError('in_time', array('0047', 'Chapter '.($i+1).':In Time'));
		}
		if ($out_flag)
		{
			$this->addError('out_time', array('0046', 'Chapter '.($i+1).':Out Time'));
		}
		if ($in_null_flag)
		{
			$this->addError('in_null_time', array('0001', 'Chapter '.($i+1).':In Time'));
		}
		if ($out_null_flag)
		{
			$this->addError('out_null_time', array('0001', 'Chapter '.($i+1).':Out Time'));
		}
		if ($title_flag)
		{
			$this->addError('Video chapter.Chapter Title', array('0035',  'Chapter '.($i+1).':Chapter Title'));
		}

		if ($in_flag || $out_flag || $in_null_flag || $out_null_flag || $title_flag) return true;
		else return false;
	}/*}}}*/

	private function del_chapter()/*{{{*/
    {
        //Model::updateBySql('update chapter set status = :st where video_id=:id',array(':st'=>AC::STATUS_DELETED,':id'=>$this->id));
		if (!strstr($this->deleted_chapters,'new') && $this->deleted_chapters)
		{
			$chapter_id = explode(",",$this->deleted_chapters);
			foreach($chapter_id as $id)
			{
				$chapter = new chapter();
				$chapter = $chapter->get($id);
				$chapter->status = AC::STATUS_DELETED;
				$chapter->modified_at = date("Y-m-d H:i:s");
				$chapter->modified_by = CommonUtils::get_user();
				$delete_id = Model::$dbo['w']->save($chapter);

				$chapter->delete_change_log();

				$chapter_language_list = chapter_language::getAll(
					array(
						'chapter_id' => $id
					)
				);
				foreach ($chapter_language_list as $chapter_language) {
					$chapter_language->delete_change_log();
				}

				$chapter_tvbcom_category_list = chapter_tvbcom_category::getAll($id);
				foreach ($chapter_tvbcom_category_list as $chapter_tvbcom_category) {
					$chapter_tvbcom_category->delete_change_log();
				}

				if ($delete_id > 0)
				{
					//$this->addInfo("chapter:".AC::LOG_OP_DELETE.":".$id, "delete chapter success", json_encode($chapter));
				}
				else
				{
					$this->addError("chapter:".AC::LOG_OP_DELETE.":".$id, "delete chapter failed", json_encode($chapter));
				}
			}
        }
	}/*}}}*/

	/*
	 * Physical delete chapter     # for bug:7529
	 * @auth    Albie Lu
	 * @date    2011-10-26
	 */
	private function del_chapter_physical()
    {
		if (!strstr($this->deleted_chapters,'new') && $this->deleted_chapters)
		{
			$chapter_id = explode(",",$this->deleted_chapters);

			foreach($chapter_id as $id)
			{
				$chapter = new chapter();
				try{
					//delete chapter-language and changelog of chapter_language
					$chapter_language_list = chapter_language::getAll(
						array(
							'chapter_id' => $id
						)
					);
					foreach ($chapter_language_list as $chapter_language) {
						$chapter_language->delete_change_log();
					}
					Model::$dbo['w']->delete('chapter_language','(chapter_id=?)',array('chapter_id'=>$id));

					//delete chapter_tvbcom_category and changelog of chapter_tvbcom_category 
					$chapter_tvbcom_category_list = chapter_tvbcom_category::getAll($id);
					foreach ($chapter_tvbcom_category_list as $chapter_tvbcom_category) {
						$chapter_tvbcom_category->delete_change_log();
					}
					Model::$dbo['w']->delete('chapter_tvbcom_category','(chapter_id=?)',array('chapter_id'=>$id));

					//delete chapter and chapter changelog
					Model::$dbo['w']->deleteInstance('chapter', $id);
					change_log::delTypeAndKeysLog('chapter', array('id'=>$id), 0);

				}catch(Exception $e){
					$this->addError("chapter:".AC::LOG_OP_DELETE.":".$id, "delete chapter failed", json_encode($chapter));
					Model::$dbo['w']->rollBack();
				}
			}
        }
	}
	
	/**
	 * move chapter from one vidoeo to other
	 */
	private function move_chapter($old_video_id, $new_video_id)/*{{{*/
	{
		$chapter = new chapter();
		$chapter_list = $chapter->getChapterList($old_video_id);
		foreach($chapter_list as $chapters)
		{
			$new_chapter = new chapter();
			$new_chapter = $new_chapter->get($chapters->id);
			$new_chapter->video_id = $new_video_id;
			$update_id = Model::$dbo['w']->save($new_chapter);

			$new_chapter->add_change_log($this->proof_programme_id);

			if ($update_id > 0)
			{
				//$this->addInfo("chapter:".AC::LOG_OP_UPDATE.":".$update_id, "move chapter success from {$old_video_id} to {$new_video_id}", json_encode($chapters));
			}
			else
			{
				$this->addError("chapter:".AC::LOG_OP_UPDATE.":".$update_id, "move chapter error from {$old_video_id} to {$new_video_id}", json_encode($chapters));
			}
		}
	}/*}}}*/
	
	
	/**
	 * add chapter
	 */
	private function add_chapter($upload)
	{
		$len = count($this->chapter_id);
		for ($i=0; $i<$len; $i++)
        {
            $in_time = array(
                array($i => $this->chapter_in_time_hour[$i]),
                array($i => $this->chapter_in_time_minute[$i]),
                array($i => $this->chapter_in_time_second[$i])
            );
            $out_time = array(
                array($i => $this->chapter_out_time_hour[$i]),
                array($i => $this->chapter_out_time_minute[$i]),
                array($i => $this->chapter_out_time_second[$i])
            );

            if (strstr($this->chapter_id[$i], "new"))
            {

                $chapter = new chapter();
				$chapter->created_at = date("Y-m-d H:i:s");
				$chapter->created_by = CommonUtils::get_user();
				$chapter->modified_at = $chapter->created_at;
				$chapter->modified_by = $chapter->created_by;
				$chapter->status = AC::STATUS_NEW;
				$chapter->available_tag_types = CommonUtils::get_allow_tags("chapter");
				$chapter->video_id = $this->id;
				$chapter->in_time = $this->num_to_sec($in_time, $i);
				$chapter->out_time  = $this->num_to_sec($out_time, $i);
				$chapter->location = '';
				//$chapter->location = $this->location[$i];
				$chapter->casts = $this->add_cast_field($this->chapter_id[$i],$this->cast_dict_id);
				$chapter->highlighted_cast_roles = '';
				$chapter->infos = empty($this->onair_episode_no) ? '' : $this->attached_info[$i];
				$chapter->tags = $this->add_tag($this->chapter_id[$i]);
               	if ($upload[$i]['flag'])
				{
					if (is_array($upload[$i]['result']))
					{
						$chapter->ii_id = $upload[$i]['result']['source_id'];
						$chapter->source_url = $upload[$i]['result']['source_url'];
						$chapter->thumbnail_url = $upload[$i]['result']['thumbnail_url'];
					}
				}

              	$chapter->id = $insert_id = Model::$dbo['w']->save($chapter);

				$chapter->add_change_log($this->proof_programme_id);
                
				if($insert_id>0)
				{
				//	$this->addInfo("chapter:".AC::LOG_OP_CREATE.":".$insert_id, "add chapter success", json_encode($chapter));
				}
				else
				{
					$this->addError("chapter:".AC::LOG_OP_CREATE.":".$insert_id, "add chapter error", json_encode($chapter));
				}
                
                $chapter_id = $insert_id;
                $this->add_chapter_category($chapter_id,$this->chapter_id[$i]);
			}
			else
			{
				$chapter = new chapter();
				$chapter = $chapter->get($this->chapter_id[$i]);
				$chapter->modified_at = date("Y-m-d H:i:s");
				$chapter->modified_by = CommonUtils::get_user();
				$chapter->status = AC::STATUS_NEW;
				$chapter->in_time = $this->num_to_sec($in_time, $i);
				$chapter->out_time  = $this->num_to_sec($out_time, $i);
				#$chapter->location = $this->location[$i];
				$chapter->casts = $this->add_cast_field($this->chapter_id[$i],$this->cast_dict_id);
				$chapter->infos = empty($this->onair_episode_no) ? '' : $this->attached_info[$i];
				$chapter->tags = $this->add_tag($this->chapter_id[$i]);
             	if (isset($upload[$i]) && $upload[$i]['flag'])
				{
					if (is_array($upload[$i]['result']))
					{
						$chapter->ii_id = $upload[$i]['result']['source_id'];
						$chapter->source_url = $upload[$i]['result']['source_url'];
						$chapter->thumbnail_url = $upload[$i]['result']['thumbnail_url'];
					}
				}

				$update_id = Model::$dbo['w']->save($chapter);

				$chapter->add_change_log($this->proof_programme_id);

				if($update_id>0)
				{
				//	$this->addInfo("chapter:".AC::LOG_OP_UPDATE.":".$this->chapter_id[$i], "update chapter success", json_encode($chapter));
				}
				else
				{
					$this->addError("chapter:".AC::LOG_OP_UPDATE.":".$this->chapter_id[$i], "update chapter failed", json_encode($chapter));
				}
                $chapter_id = $this->chapter_id[$i];

                $this->add_chapter_category($chapter_id,$this->chapter_id[$i]);
			}


			//handle multiple language
			$this->add_chapter_language($chapter_id,$i);
            $this->add_en_chapter($chapter_id,$i);

            //$this->tvbcom_cat_id[]
            $primary_key = array(
                'id' => $chapter_id
            );
            $fields = array(
                'thumbnail_url', 
                'source_url', 
                'location', 
                'highlighted_cast_roles', 
                'casts', 
                'available_tag_types', 
                'tags', 
                'infos'
            );
            CommonUtils::filterC2A0('chapter', $primary_key, $fields);
            
            $primary_key = array(
                'chapter_id' => $chapter_id
            );
            $fields = array(
                'title', 
                'description'
            );
            CommonUtils::filterC2A0('chapter-language', $primary_key, $fields);
		}
	}


	/**
	 * add ch chapter
	 */
	private function add_chapter_language($chapter_id, $i)/*{{{*/
	{
		$chapter_language = new chapter_language();

		if (strstr($this->chapter_id[$i], "new"))
		{
			$chapter_language->chapter_id = $chapter_id;
			$chapter_language->language_id = language::getLanguageID(AC::DEFAULT_LANGUAGE);
			$chapter_language->title = trim($this->chapter_title_cn[$i]);
			$chapter_language->description = $this->chapter_description_cn[$i];
			$new_chapter_id = Model::$dbo['w']->save($chapter_language);
			if ($new_chapter_id >= 0)
			{
				//$this->addInfo("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language error", json_encode($chapter_language));
			}
		}
		else
		{
			$chapter_language = $chapter_language->getLangChapterByID($chapter_id,language::getLanguageID(AC::DEFAULT_LANGUAGE));
			$chapter_language->title = trim($this->chapter_title_cn[$i]);
			$chapter_language->description = $this->chapter_description_cn[$i];
			$update_id = Model::$dbo['w']->save_by_fields($chapter_language, array('chapter_id','language_id'));
			if ($update_id >= 0)
			{
				//$this->addInfo("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language failed", json_encode($chapter_language));
			}
		}
	
		$chapter_language->add_change_log($this->proof_programme_id);
	}/*}}}*/
	/**
	 * add en chapter
	 */
	private function add_en_chapter($chapter_id, $i)/*{{{*/
	{
		$chapter_language = new chapter_language();

		if (strstr($this->chapter_id[$i],"new"))
		{
			$chapter_language->chapter_id = $chapter_id;
			$chapter_language->language_id = language::getLanguageID(AC::LANGUAGE_EN);
			$chapter_language->title = trim($this->chapter_title_en[$i]);
			$chapter_language->description = $this->chapter_description_en[$i];
			$new_chapter_id = Model::$dbo['w']->save($chapter_language);
			if ($new_chapter_id >= 0)
			{
				//$this->addInfo("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_CREATE.":".$chapter_id, "add chapter language error", json_encode($chapter_language));
			}
		}
		else
		{
			$chapter_language = $chapter_language->getLangChapterByID($chapter_id,language::getLanguageID(AC::LANGUAGE_EN));
			if (!$chapter_language) {
				$chapter_language = new chapter_language();
				$chapter_language->chapter_id = $chapter_id;
				$chapter_language->language_id = language::getLanguageID(AC::LANGUAGE_EN);
			}
			
			$chapter_language->title = trim($this->chapter_title_en[$i]);
			$chapter_language->description = $this->chapter_description_en[$i];
			$update_id = Model::$dbo['w']->save_by_fields($chapter_language, array('chapter_id','language_id'));
			if ($update_id >= 0)
			{
				//$this->addInfo("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language success", json_encode($chapter_language));
			}
			else
			{
				$this->addError("chapter-language:".AC::LOG_OP_UPDATE.":".$chapter_id, "update chapter language failed", json_encode($chapter_language));
			}
		}

		$chapter_language->add_change_log($this->proof_programme_id);
	}
/*}}}*/

    private function add_chapter_category($chapter_id, $key)
    {
        $chapter_tvbcom_category = new chapter_tvbcom_category();

		// delete change_log by donald
		$chapter_tvbcom_category_list = $chapter_tvbcom_category->getAll($chapter_id);
		foreach ($chapter_tvbcom_category_list as $chapter_tvbcom_category_detail) {
			$chapter_tvbcom_category_detail->add_change_log($this->proof_programme_id, 0);
		}

        $chapter_tvbcom_category->delBySql($chapter_id);

        if(isset($this->tvbcom_cat_id[$key])) {
            foreach ($this->tvbcom_cat_id[$key] as $key=>$id) {
                $chapter_tvbcom_category->chapter_id = $chapter_id;
                $chapter_tvbcom_category->category_id = $id;
                $chapter_tvbcom_category->rank = $key+1;
                $ret = Model::$dbo['w']->save($chapter_tvbcom_category);

				$chapter_tvbcom_category->add_change_log($this->proof_programme_id);

                if ($ret >= 0) {
                    //$this->addInfo("chapter-tvbcom_category:".AC::LOG_OP_UPDATE.":".$chapter_id,
                    //  "update chapter_tvbcom category success", json_encode($chapter_tvbcom_category));
                } else {
                    $this->addError("chapter-tvbcom_category:".AC::LOG_OP_UPDATE.":".$chapter_id,
                        "update chapter_tvbcom category failed", json_encode($chapter_tvbcom_category));
                }
            }
        }
    }

	private function init_page_data()
    {
		$action = new VideoGetAction();
		if($this->act == 'add'){
			$action->act = 'add';
		}else{
			$action->id = $this->id;
			$action->act = 'edit';

            $sql_eid = 'select e.onair_episode_no from episode e left join `episode-video` ev on e.id=ev.episode_id where ev.video_id = :vid';
            $data = Model::selectBySql($sql_eid,array(':vid'=>$this->id));
            $this->setData("exist_onair_episode_no", isset($data[0]) ? $data[0]['onair_episode_no'] : '');
            $this->setData('eps',episode::getEpisodeNumByProgrammeId($this->programme_id));
        }
        //$action->tag = $this->get_tags();
		$action->execute();
    	$en_langid = language::getLanguageID(AC::LANGUAGE_EN);
		$zh_langid = language::getLanguageID(AC::LANGUAGE_ZH);
	
		$old_data = $action->getData();
		
        $old_data['video']['video_language'][1]['title'] = $this->title;
        $old_data['video']['mdes_status'] = $this->mdes_status;       
        $old_data['video']['copyright'] = empty($this->copyright_owner) ? 'TVB' : trim($this->copyright_owner);      
       // $video_casts = $this->add_cast_field(NULL, $this->cast_dict_id);
        if (!empty($video_casts)) {
            $old_data['video']['casts'] = cast_dictionary::getCastListById(explode(',', $video_casts));
        } else {
            $old_data['video']['casts'] = array();
        }
        $old_data['video']['premium_flag'] = isset($this->premium_flag) ? $this->premium_flag : 0;
        $old_data['video']['video_type'] = isset($this->video_type) ? $this->video_type : 'o';
        $old_data['video']['subscription_flag'] = !empty($this->premium_items) && in_array('subscription',$this->premium_items)? 1: 0;
        $old_data['video']['ppv_flag'] = !empty($this->premium_items) && in_array('ppv',$this->premium_items)? 1: 0;

        $old_data['video']['subtitle_cn'] = $this->subtitle_cn;
        $old_data['video']['subtitle_en'] = $this->subtitle_en;

        $tag_type = 13;
        $video           =   new video();
        #$new_tags = isset($this->new_tag) ? $this->new_tag : '';
        $tags = isset($this->tag) ? $this->tag : '';
        #$all_new_tags = array($tag_type=>array());
        #$all_tags = array();
        $old_tags = array($tag_type=>array());

        if(isset($tags[$tag_type]))
        {
            foreach($tags[$tag_type] as $_tag)
            {
				if( is_array($_tag) ){
					$_tag = $_tag['new'];
					$flag = trim(urldecode(trim($_tag)));
					if(!empty($flag))
					{
						$old_tags[$tag_type][] = array(
							'is_new'        => 1,
							'id'            =>  $_tag, 
							'system_label'  => urldecode(trim($_tag))
						);
					}
				}
				else
				{
					$_tag = intval($_tag);
					$sql = 'SELECT system_label FROM tag t where id = :tid';
					$data = Model::selectBySql($sql,array(':tid'=>$_tag));
					if(!empty($data))
					{
						$old_tags[$tag_type][] = array(
							'id'			=> $_tag, 
							'system_label'	=> $data[0]['system_label']
						);  
					}
				}
			}
        }

        $all_tags = $old_tags;

        if(empty($old_data['video']['programme_id']))
        {
            $old_data['video']['programme_id'] = $this->programme_id; 
        }
       
        if (is_array($this->first_time_onair))
		{
			$old_data['video']['first_time_onair'] = CommonUtils::formatDate(implode(' ', $this->first_time_onair));
		}
		else
		{
			$old_data['video']['first_time_onair'] = CommonUtils::formatDate($this->first_time_onair);
		}
		if (is_array($this->online_date_time))
		{
			$old_data['video']['publish_datetime'] = CommonUtils::formatDate(implode(' ', $this->online_date_time));
		}
		else
		{
			$old_data['video']['publish_datetime'] = CommonUtils::formatDate($this->online_date_time);
		}
		if (is_array($this->offline_date_time))
		{
			$old_data['video']['expire_datetime'] = CommonUtils::formatDate(implode(' ', $this->offline_date_time));
		}
		else
		{
			$old_data['video']['expire_datetime'] = CommonUtils::formatDate($this->offline_date_time);
		}

        if ('allow' ==  $this->country_allow_deny) {
            $old_data['video']['global_country_allow_deny'] = 0; 
            $old_data['video']['global_country']   =   is_null($this->country) ? "" :  $this->country;
        } else {
            $old_data['video']['global_country_allow_deny'] = 1; 
            $old_data['video']['global_country']   =   is_null($this->country) ? "" :  $this->country;
        }
        
		foreach ($old_data as $object=>$data)
		{
			$this->setData($object, $data);
        }


        $this->setData('init_seo_tag',$all_tags);
		//jump page
		$this->setData('id', $this->id);
		$this->setData('type', 'video');
		$this->setData('act', $this->act);
		$this->setData('from', $this->from);
		$this->setData('init_onair_episode_no', $this->onair_episode_no);
        $this->init_chapter_data($old_data);
        $this->__init_video_subscription();
        $this->__init_video_ppv();
	}

	/**
	 * init chapter page data
	 */
	private function init_chapter_data($old_data)
	{
	/*	$action = new VideoGetAction();
		$action->id = $this->id;
		$action->act = 'edit';
		$action->execute();
        
        $old_data = $action->getData();
     */
		$chapter = new chapter();
		$chapter_list = $chapter->getChapterList($this->id);

		$new_chapter_ids = array();
		$old_chapter_ids = array();
		$del_chapter_ids = array();

		foreach ($chapter_list as $chapter)
		{
			$new_chapter_ids[] = $chapter->id;
        }

		//retain input content
		$chapter_list = $casts =  $init_tag_list = $tvb_category_arr = array();
		$len = count($this->chapter_id);
		for($i=0; $i<$len; $i++)
		{
           $in_time = array(
                array($i => $this->chapter_in_time_hour[$i]),
                array($i => $this->chapter_in_time_minute[$i]),
                array($i => $this->chapter_in_time_second[$i])
            );
            $out_time = array(
                array($i => $this->chapter_out_time_hour[$i]),
                array($i => $this->chapter_out_time_minute[$i]),
                array($i => $this->chapter_out_time_second[$i])
            );

			if (strstr($this->chapter_id[$i], 'new'))
			{
				$chapter = new chapter();
				$chapter->id = $this->chapter_id[$i];
				$title_cn = empty($this->chapter_title_cn[$i]) ? '' : $this->chapter_title_cn[$i];
				$title_en = empty($this->chapter_title_en[$i]) ? '' : $this->chapter_title_en[$i];
                $chapter->chapter_title = $title_cn."\n\t".$title_en;
				$chapter_description_cn = empty($this->chapter_description_cn[$i]) ? '' : $this->chapter_description_cn[$i];
				$chapter_description_en = empty($this->chapter_description_en[$i]) ? '' : $this->chapter_description_en[$i];
                $chapter->chapter_description = $chapter_description_cn."\n\t".$chapter_description_en;
				$chapter->created_at = date("Y-m-d H:i:s");
				$chapter->created_by = CommonUtils::get_user();
				$chapter->modified_at = $chapter->created_at;
				$chapter->modified_by = $chapter->created_by;
				$chapter->status = AC::STATUS_NEW;
				$chapter->available_tag_types = CommonUtils::get_allow_tags("chapter");
				$chapter->video_id = $this->id;
				if ($this->chapter_in_time_hour[$i] == '' && $this->chapter_in_time_minute[$i] == '' && $this->chapter_in_time_second[$i] == '')
				{
					$chapter->in_time  = 0;
				}
				else
				{

					$chapter->in_time = $this->num_to_sec($in_time, $i);
				}
				if ($this->chapter_out_time_hour[$i] == '' && $this->chapter_out_time_minute[$i] == '' && $this->chapter_out_time_second[$i] == '')
				{
					$chapter->out_time  = 0;
				}
				else
				{
					$chapter->out_time  = $this->num_to_sec($out_time, $i);
                }
				$chapter->infos = empty($this->onair_episode_no) ? '' : $this->attached_info[$i];
				$chapter->casts = $this->add_cast_field($this->chapter_id[$i],$this->cast_dict_id);
                if (!empty($chapter->casts)) {
                    $casts['chapter'][$chapter->id] = cast_dictionary::getCastListById(explode(',', $chapter->casts));
                } else {
                    $casts['chapter'][$chapter->id] = array();

                }

				$chapter->highlighted_cast_roles = '';
				$chapter->thumbnail_url = '';
				$chapter->source_url = '';

                //$tvb_category_arr[$this->chapter_id[$i]] = $this->init_chapter_category($this->chapter_id[$i]);
				$init_tag_list[$this->chapter_id[$i]] = $this->init_tag($this->chapter_id[$i], $i);
				$chapter_list[] = $chapter;
			}
			else
			{
				$chapter = new chapter();
				$chapter = $chapter->get($this->chapter_id[$i]);
				$chapter->modified_at = date("Y-m-d H:i:s");
				$chapter->modified_by = CommonUtils::get_user();
				if ($this->chapter_in_time_hour[$i] == '' && $this->chapter_in_time_minute[$i] == '' && $this->chapter_in_time_second[$i] == '')
				{
					$chapter->in_time  = 0;
				}
				else
				{
					$chapter->in_time = $this->num_to_sec($in_time, $i);
				}

				if ($this->chapter_out_time_hour[$i] == '' && $this->chapter_out_time_minute[$i] == '' && $this->chapter_out_time_second[$i] == '')
				{
					$chapter->out_time  = 0;
				}
				else
				{
					$chapter->out_time  = $this->num_to_sec($out_time, $i);
                }
                $chapter->casts = $this->add_cast_field($this->chapter_id[$i],$this->cast_dict_id);
                if (!empty($chapter->casts)) {
                    $casts['chapter'][$chapter->id] = cast_dictionary::getCastListById(explode(',', $chapter->casts));
                } else {
                    $casts['chapter'][$chapter->id] = array();

                }

				$chapter->infos = empty($this->onair_episode_no) ? '' : $this->attached_info[$i];
				$init_tag_list[$this->chapter_id[$i]] = $this->init_tag($this->chapter_id[$i], $i);
        	    $title_cn = empty($this->chapter_title_cn[$i]) ? '' : $this->chapter_title_cn[$i];
				$title_en = empty($this->chapter_title_en[$i]) ? '' : $this->chapter_title_en[$i];
                $chapter->chapter_title = $title_cn."\n\t".$title_en;
				$chapter_description_cn = empty($this->chapter_description_cn[$i]) ? '' : $this->chapter_description_cn[$i];
				$chapter_description_en = empty($this->chapter_description_en[$i]) ? '' : $this->chapter_description_en[$i];
                $chapter->chapter_description = $chapter_description_cn."\n\t".$chapter_description_en;
                
                //$tvb_category_arr[$this->chapter_id[$i]] = $this->init_chapter_category($this->chapter_id[$i]);
			
				$chapter_list[] = $chapter;
				$old_chapter_ids[] = $this->chapter_id[$i];
			}
            
                $tvb_category_arr[$this->chapter_id[$i]] = $this->init_chapter_category($this->chapter_id[$i]);
		}
       	$old_data['chapter_list'] = $chapter_list;

		$this->setData('init_tag_list', $init_tag_list);
        $this->setData('init_casts', $casts);
        $this->setData("init_tvb_category_list", $tvb_category_arr);
		

		foreach ($old_data as $object=>$data)
		{
			$this->setData($object, $data);
		}
		//delete chapter id
		if (empty($old_chapter_ids) && !empty($new_chapter_ids))
		{
			$del_chapter_ids = $new_chapter_ids;
		}
		else
		{
			$del_chapter_ids = array_diff_assoc($new_chapter_ids, $old_chapter_ids);	
		}
		$this->setData('deleted_chapters', implode(",", $del_chapter_ids));
	}

    private function init_chapter_category($chapter_id)
    {
        $ret = array();
        if (!empty($this->tvbcom_cat_id)) {
            $this->tvbcom_cat_id = array_unique($this->tvbcom_cat_id);
            if(!empty($this->tvbcom_cat_id[$chapter_id])){
                foreach ($this->tvbcom_cat_id[$chapter_id] as $key=>$id) {
                   
                    $sql = 'SELECT * FROM tvbcom_category t where id = :id ';
                    $data = Model::selectBySql($sql,array(':id'=>$id));
                    $label = $data[0]['system_label'];
                    $parent_id = $data[0]['parent_id'];
                    $parent_name = tvbcom_category::getParentName($label, $parent_id);

                    $ret[] =  array("id"=>$id,"system_label"=>$parent_name." ".$label);
                }
            }
        }
        return $ret;
        
    }

	/**
	 * concurrent handle
	 */
	private function check_concurrent()
	{
		$video = new video();
		$video_detail = $video->get($this->id);

		if ($video_detail->modified_at == $this->modified_at)
		{
			return false;
		}
		else
		{
			return true;
		}
	}

    private function __check_ppv_datetime()
    {
        $flag = true;
        if (!empty($this->ppv_publish_datetime) && !empty($this->ppv_expire_datetime)) {
            if ($this->ppv_publish_datetime > $this->ppv_expire_datetime) {
                $this->addError('Online Date Time / Offline Date Time', array('0205', 'Pay-Per-View Online Date Time / Offline Date Time'));
                $flag =  FALSE;
            }
        }
        else
        {
            $this->addError('Online Date Time / Offline Date Time', array('0402', 'Pay-Per-View Online Date Time / Offline Date Time'));
            $flag =  false; 
        }
        return $flag;
    }
    private function __check_subscription_datetime()
    {
        $flag = true;
        if ($this->subscription_publish_datetime && $this->subscription_expire_datetime) {
            if ($this->subscription_publish_datetime > $this->subscription_expire_datetime) {
                $this->addError('Online Date Time / Offline Date Time', array('0205', 'Subscription Online Date Time / Offline Date Time'));
                $flag = FALSE;
            }
        }
        else
        {
            $this->addError('Online Date Time / Offline Date Time', array('0402', 'Subscription Online Date Time / Offline Date Time'));
            $flag =  false; 
        }
        return $flag;
    }
    
    private function __update_video_premium()
    {
        $programme = new programme;
        $programme_detail = $programme->get($this->programme_id);
        if ($programme_detail->premium_flag) {
            $video_premium = new video_premium();
            $premium = $video_premium->get($this->id); 
            if (empty($premium)) {
                $video_premium->set($this);
                $rs = $video_premium->insert($video_premium);
                if(!mysql_error()) {
				    $this->addInfo("video_premium:".AC::LOG_OP_CREATE.":".$this->id, "create video premium success", json_encode($video_premium));
                } else {
				    $this->addError("video_premium:".AC::LOG_OP_CREATE.":".$this->id, "create video premium failed", json_encode($video_premium));
				}
            } else {
                $video_premium->set($this);
                Model::diff($premium, $video_premium);
                $rs = $video_premium->update($premium);
                if ($rs) {
				    $this->addInfo("video_premium:".AC::LOG_OP_UPDATE.":".$this->id, "update video premium success", json_encode($premium));
                } else {
				    $this->addError("video_premium:".AC::LOG_OP_UPDATE.":".$this->id, "update video premium success", json_encode($premium));
                }
            }

			if ($video_premium->ppv_flag || $video_premium->subscription_flag) {
				$video_premium->add_change_log($this->proof_programme_id);
			}
        }
    }


    private function __update_video_ppv()
    {
        $programme = new programme;
        $programme_detail = $programme->get($this->programme_id);

        if ($programme_detail->premium_flag) {
            $video_ppv = new video_ppv;
            $ppv = $video_ppv->get($this->id); 
            $premium_items = is_array($this->premium_items) ? $this->premium_items : array();
            if(!in_array('ppv',$premium_items))
            {
                if(!empty($ppv))
                {
                    $video_ppv->delete($this->id);
					$ppv->add_change_log($this->proof_programme_id, 0);
                }
                return;
            }
            if (empty($ppv)) {
                $video_ppv->set($this);
                $rs = $video_ppv->insert($video_ppv);
                if (!mysql_error()) {
				    $this->addInfo("video_ppv:".AC::LOG_OP_CREATE.":".$this->id, "create video pay per view success", json_encode($video_ppv));
                } else {
				    $this->addError("video_ppv:".AC::LOG_OP_CREATE.":".$this->id, "create video pay per view failed", json_encode($video_ppv));
                }
            } else {
                $video_ppv->set($this);
                Model::diff($ppv, $video_ppv);
                $rs = $video_ppv->update($ppv);
                if ($rs) {
				    $this->addInfo("video_ppv:".AC::LOG_OP_UPDATE.":".$this->id, "update video pay per view success", json_encode($ppv));
                } else {
				    $this->addError("video_ppv:".AC::LOG_OP_UPDATE.":".$this->id, "update video pay per view success", json_encode($ppv));
                }
            }
			$video_ppv->add_change_log($this->proof_programme_id);
        }
    }

    private function __update_video_subscription()
    {
        $programme = new programme;
        $programme_detail = $programme->get($this->programme_id);

        if ($programme_detail->premium_flag) {
            $video_subscription = new video_subscription;
            $subscription = $video_subscription->get($this->id); 
            $premium_items = is_array($this->premium_items) ? $this->premium_items : array();
            if(!in_array('subscription',$premium_items))
            {
                if(!empty($subscription))
                {
                    $video_subscription->delete($this->id);
					$subscription->add_change_log($this->proof_programme_id, 0);
                }
                return;
            }

            if (empty($subscription)) {
                $video_subscription->set($this);
                $rs = $video_subscription->insert($video_subscription);
                if (!mysql_error()) {
				    $this->addInfo("video_subscription:".AC::LOG_OP_CREATE.":".$this->id, "create video subscription success", json_encode($video_subscription));
                } else {
				    $this->addError("video_subscription:".AC::LOG_OP_CREATE.":".$this->id, "create video subscription failed", json_encode($video_subscription));
                }
            } else {
                $video_subscription->set($this);
                Model::diff($subscription, $video_subscription);
                $rs = $video_subscription->update($subscription);
                if ($rs) {
				    $this->addInfo("video_subscription:".AC::LOG_OP_UPDATE.":".$this->id, "update video subscription success", json_encode($subscription));
                } else {
				    $this->addError("video_subscription:".AC::LOG_OP_UPDATE.":".$this->id, "update video subscription success", json_encode($subscription));
                }
            }
			$video_subscription->add_change_log($this->proof_programme_id);
        }
    }

    private function __init_video_subscription()
    {
        $subscription = array();
        $subscription['publish_datetime'] = $this->subscription_publish_datetime;
        $subscription['expire_datetime'] = $this->subscription_expire_datetime;
        $subscription['free'] = $this->subscription_free;
        $subscription['subscription_country'] = $this->subscription_country;
        $subscription['subscription_country_allow_deny'] = $this->subscription_country_allow_deny;
        $this->setData('video_subscription', $subscription);
    }

    private function __init_video_ppv()
    {
        $ppv = array();
        $ppv['publish_datetime'] = $this->ppv_publish_datetime;
        $ppv['expire_datetime'] = $this->ppv_expire_datetime;
        $ppv['ppv_country'] = $this->ppv_country;
        $ppv['ppv_country_allow_deny'] = $this->ppv_country_allow_deny;
        $this->setData('video_ppv', $ppv);
    }
}
?>
